<?php


namespace app\shop\model;

use app\shop\model\SpecItemModel;
use think\Model;

class SpecModel extends Model
{
    protected $table = 'dp_spec';
    protected $pk = 'id';
    protected $field = true;


    public function type()
    {
        return $this->hasOne('GoodsTypeModel','id','type_id')->bind(['type_name'=>'name']);
    }

    public static function getList($type_id=0)
    {
        if($type_id==0){
            return self::with('type')->paginate(10);
        }else{
            return self::with('type')->where('type_id',$type_id)->paginate(10);
        }
    }

    public static function getOne($id=0)
    {
        $res = self::get($id);
        $item = SpecItemModel::getRes($id);

        $res['spec_item'] = implode(',',$item);
        return $res;
    }

    public static function saveSpec($data, $id=0)
    {
        $item = explode(",",$data['spec_item']);
        unset($data['spec_item']);
        unset($data['__token__']);
        if($id==0){
            $res = self::insertGetId($data);
            $id = $res;
        }else{
            $res = self::where('id',$id)->update($data);
        }
        $un = SpecItemModel::addItem($item,$id);
        if($res||$un){
            return 1;
        }else{
            return 0;
        }

    }

    public static function del($id=0)
    {
        $res = self::destroy($id);
        if($res){
            SpecItemModel::where('spec_id',$id)->delete();
        }
        return $res;
    }

    public static function getRes()
    {
        return self::column('id,name');
    }

    public static function getColumn()
    {
        return self::column('name','id');
    }

    public static function getIdList($type_id)
    {
        return self::where("type_id",$type_id)->order('sort desc')->column('id');
    }


}